package com.hanxiaozhang.transaction.test;

import com.hanxiaozhang.common.DictTwoDO;
import com.hanxiaozhang.common.DictTwoDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalTime;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author hanxinghua
 * @create 2022/1/26
 * @since 1.0.0
 */
@Slf4j
@Service
public class TxTestInnerServiceImpl implements TxTestInnerService {

    @Resource
    private DictTwoDao dictTwoDao;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void test() {
        DictTwoDO name = DictTwoDO.builder()
                .name("name").description("你好")
                .build();

        dictTwoDao.save1(name);
        log.info(LocalTime.now().toString());
        try {
            TimeUnit.SECONDS.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info(LocalTime.now().toString());
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void required1() {

        dictTwoDao.save(setDict("inner is required"));
        throw new RuntimeException();
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void requiredNew1() {
        dictTwoDao.save(setDict("inner is requiredNew"));
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.SUPPORTS)
    public void support1() {
        dictTwoDao.save(setDict("inner is support"));
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.NOT_SUPPORTED)
    public void notSupport1() {
        dictTwoDao.save(setDict("inner is notSupport"));
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.MANDATORY)
    public void mandatory1() {
        dictTwoDao.save(setDict("inner is mandatory"));
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.NEVER)
    public void never1() {
        dictTwoDao.save(setDict("inner is never"));
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.NESTED)
    public void nested1() {
        dictTwoDao.save(setDict("inner is nested"));
        throw new RuntimeException();
    }

    private DictTwoDO setDict(String name) {
        return DictTwoDO.builder()
                .name(name)
                .createDate(new Date())
                .build();
    }

}
